package com.example.testdemo.pools;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.example.testdemo.TankGameActivity;
import com.example.testdemo.kstatic.sprite.ItemSprite;
import com.example.testdemo.manager.ResourcesManager;
import com.example.testdemo.manager.ScenesManager;
import com.example.testdemo.resources.ItemResources;
import com.example.testdemo.scenes.stage.BaseStage;

public class ItemPools {
    public static final int STAGE_1_ITEM_COUNT = 2;

    private TankGameActivity mActivity;
    private int mStage = 0;
    private ItemResources mResources = null;
    private List<ItemSprite> mItemList = null;

    public ItemPools(TankGameActivity activity, int whichStage) {
        mActivity = activity;
        mStage = whichStage;
        mResources = (ItemResources) ResourcesManager.getInstance()
                .getResources(ResourcesManager.RESOURCES_ITEMS);
    }

    public void createItemSprites() {
        switch (mStage) {
        case ScenesManager.SCENE_STAGE_1:
            mItemList = createStage1Sprite();
            break;
        case ScenesManager.SCENE_STAGE_2:
            mItemList = createStage1Sprite();
            break;
        }
    }

    public List<ItemSprite> getItemList() {
        return mItemList;
    }

    private List<ItemSprite> createStage1Sprite() {
        List<ItemSprite> list = new ArrayList<ItemSprite>(STAGE_1_ITEM_COUNT);
        Random random = new Random(System.currentTimeMillis());
        int[] rangeDefence = new int[] { 0, 5 };
        int[] rangeSpeed = new int[] { 6, 9 };

        final int MAX_RANGE = 9;
        ItemSprite item = null;
        for (int i = 0; i < STAGE_1_ITEM_COUNT; i++) {
            int rInt = random.nextInt(MAX_RANGE);
            if (rInt >= rangeDefence[0] && rInt <= rangeDefence[1]) {
                item = new ItemSprite(0, 0, mResources.mRegionDefence,
                        mActivity.getVertexBufferObjectManager());
                item.setItemType(ItemSprite.TYPE_DEFENCE);
            } else if (rInt >= rangeSpeed[0] && rInt <= rangeSpeed[1]) {
                item = new ItemSprite(0, 0, mResources.mRegionSpeed,
                        mActivity.getVertexBufferObjectManager());
                item.setItemType(ItemSprite.TYPE_SPEED);
            }
            BaseStage scene = (BaseStage) ScenesManager.getInstance().getScene(
                    ScenesManager.SCENE_STAGE_1);
            item.setTag(scene.getSpriteTag().ITEM_START + i);
            item.setVisible(false);
            scene.attachChild(item);
            list.add(item);
        }

        return list;
    }

    public void free() {
        if (mItemList != null) {
            for (ItemSprite item : mItemList) {
                item.detachSelf();
                item.dispose();
            }
            mItemList.clear();
        }
    }
}
